package com.share.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.util.StringUtils;

import java.util.Collection;

/**
 * @author syq
 * @data 2019/8/9
 */
@Slf4j
public class ApplicationUtil implements ApplicationContextAware {
    private static ApplicationContext context = null;
    private static String profile = null;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.context = applicationContext;
    }

    /*获取配置中的值*/
    public static String getEnvironmentProperty(String key) {
        if (StringUtils.isEmpty(key)) {
            return null;
        } else if (context == null) {
            return null;
        } else {
            return context.getEnvironment().getProperty(key);
        }
    }

    public static String getEnvironmentProperty(String key, String def) {
        String value = getEnvironmentProperty(key);
        if (StringUtils.isEmpty(value)) {
            return def;
        } else {
            return value;
        }
    }

    /*修改熟悉的值*/
    public static String setEnvironmentProperty(String key, String value) {
        ((ConfigurableApplicationContext) context).getEnvironment().getSystemProperties().put(key, value);
        return getEnvironmentProperty(key);
    }

    public static <T> T getBean(String name) {
        if (context == null) {
            return null;
        }
        return (T) context.getBean(name);
    }

    public static <T> T getBean(Class<T> cls) {
        if (context == null) {
            return null;
        }
        return (T) context.getBean(cls);
    }

    public static <T> Collection<T> getBeansOfType(Class<T> calzz) {
        if (context == null) {
            return null;
        }
        return context.getBeansOfType(calzz).values();
    }
}
